local SourceModifierList = require("util/sourcemodifierlist")

local function clamp(value, min, max)
    if value < min then
        return min
    elseif value > max then
        return max
    else
        return value
    end
end
local function obsword_findplayers(inst)
end
local mount_re = 0
local function obsword_repair(owner)
    local body = owner.components.inventory:GetEquippedItem(EQUIPSLOTS.BODY)
    local head = owner.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
    --#region 修理盔甲以及耐久 将同时基于基础以及百分比的修复
    if head then
        mount_re = mount_re + 1
        if head.components.armor then
            head.components.armor:Repair(35)
            local op = head.components.armor:GetPercent()
            head.components.armor:SetPercent(op + 0.035)
            owner.components.obrsword_power:DoDelta(-6)
        end
        if head.components.finiteuses then
            mount_re = mount_re + 1
            head.components.finiteuses:Repair(3.5)
        end
    end
    if body then
        mount_re = mount_re + 1
        if body.components.armor then
            body.components.armor:Repair(35)
            local op = body.components.armor:GetPercent()
            body.components.armor:SetPercent(op + 0.035)
            owner.components.obrsword_power:DoDelta(-6)
        end
        if body.components.finiteuses then
            mount_re = mount_re + 1
            body.components.finiteuses:Repair(3.5)
        end
    end
    return mount_re
end
local function obsword_orangerepair(owner)
    local body = owner.components.inventory:GetEquippedItem(EQUIPSLOTS.BODY)
    local head = owner.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
    if head then
        if head:HasTag("ruins") then
            if head.components.armor then
                local op1 = math.random(45, 60)
                head.components.armor:Repair(op1)

                owner.components.obrsword_power:DoDelta(-4)
            end
        end
    end
    if not body then
        return
    end
    if body:HasTag("ruins") or body:HasTag("marble") then
        if body.components.armor then
            local op2 = math.random(35, 50)
            body.components.armor:Repair(op2)
            owner.components.obrsword_power:DoDelta(-6)
        end
    end
end
local tools = require 'util/tools'
local obrsword_gempower = {
    can_tri_circle_dmg = 3,
    fightbgmcd = true, --战斗短暂bgm刷新cd
    firstgem = nil,
    ["redgem"] = {
        -- 三层破败灼烧被动15s  2，3每层叠加50%  随机回血3滴
        extarpower = 15,
        onattack = function(owner, target, inst)
            if math.random(1, 8) < 4 then
                owner.components.health:DoDelta(3)
            end
            local damage = (8 + 0.01 * target.components.health.currenthealth) or 8
            if target:HasTag("bee") then
                damage = (16 + 0.01 * target.components.health.currenthealth) or 16
            end

            if not target.components.obrsword_powergem_sign then
                target:AddComponent("obrsword_powergem_sign")

                target.components.obrsword_powergem_sign.firelevel = 1
            else
                target.components.obrsword_powergem_sign.firelevel = clamp(
                    target.components.obrsword_powergem_sign.firelevel + 1, 0, 3)
            end
            local level = target.components.obrsword_powergem_sign.firelevel
            if target.components.health then
                if target.firetask ~= nil then
                    target.firetask:Cancel()
                    target.firetask = nil
                end
                target.firetask = target:DoPeriodicTask(1.5, function()
                    if target.components.health and target:IsValid() then
                        target.components.health:DoDelta(-level * damage)
                        target.fx_fire_atk = SpawnPrefab('obrsword_powerchange_firesign')
                        target.fx_fire_atk.entity:SetParent(target.entity)
                        target:DoTaskInTime(15, function(target)
                            if target.firetask ~= nil then
                                target.firetask:Cancel()
                                target.firetask = nil
                            end
                        end)
                    end
                end)
            end
        end,
        extratalent = function(inst) end,
        cancelextratalent = function(inst) end,
    },

    ["bluegem"] = {
        -- 微量能量  0.5层冰冻效果（火系四倍）降温
        extarpower = 15,
        onattack = function(owner, target, inst)
            if target.components.sleeper ~= nil and target.components.sleeper:IsAsleep() then -- 目标有睡眠组件 且目标是睡着的
                target.components.sleeper:WakeUp()                                            -- 惊醒
            end
            if target.components.burnable ~= nil then                                         -- 目标有可燃烧组件
                if target.components.burnable:IsBurning() then                                -- 是否在燃烧的
                    target.components.burnable:Extinguish()                                   -- 熄灭（水火不融）
                elseif target.components.burnable:IsSmoldering() then                         -- 是否是缓燃的
                    target.components.burnable:SmotherSmolder()                               -- 缓燃
                end
            end

            if target.sg ~= nil and not target.sg:HasStateTag("frozen") then -- 目标有sg且没有冻结的状态标记
                target:PushEvent("attacked", {
                    attacker = target,
                    damage = 0
                }) -- 推动事件 攻击
            end
            -- 克制龙蝇战的冰冻能力
            if target.components.freezable ~= nil and target.components.health.currenthealth > 0 then -- 目标有可冻结组件且存活
                if target:HasTag("lavae") or target:HasTag("dragonfly") then
                    target.components.freezable:AddColdness(2)
                    target.components.freezable:SpawnShatterFX() -- 生成粉碎效果
                    owner.components.obrsword_power:DoDelta(-5)
                else
                    target.components.freezable:AddColdness(0.5)
                    owner.components.obrsword_power:DoDelta(-1)
                end
            end
            -- 降温能力
            if owner.components.temperature ~= nil then
                local current = owner.components.temperature:GetCurrent()
                if current == nil then
                    return
                end

                if current > 45 and target.components.combat then
                    owner.components.temperature:SetTemperature(current - 5) -- 体温
                end
            end
        end,
        extratalent = function(inst) end,
        cancelextratalent = function(inst) end,
    },
    ["purplegem"] = {


        -- 少量能量  少量额外伤害  暗影夺萃回san
        extarpower = 30,
        onattack = function(owner, target, inst)
            if target.components.health and target:IsValid() then
                target.components.health:DoDelta(-55)
            end
            if target:HasTag("monster") or target:HasTag("shadow") then
                local max = target.components.health.maxhealth
                local numsan = clamp(1 + 0.01 * max, 0, 10)
                owner.components.sanity:DoDelta(numsan)
                -- 灵魂出窍
                SpawnPrefab("shadowhand_fx").Transform:SetPosition(target.Transform:GetWorldPosition())
            else
                owner.components.sanity:DoDelta(0.75)
            end
        end,
        extratalent = function(inst) end,
        cancelextratalent = function(inst) end,
    },
    ["orangegem"] = {
        -- 少量能量    1/3概率产生沙刺攻击   攻击增加移速
        extarpower = 40,
        extratalent = function(inst)
            local inst = inst.components.inventoryitem.owner
            inst:AddTag("obsword_orangegem_reduction")
            inst.components.health.externalabsorbmodifiers:SetModifier(inst, 0.5, "orangegem_reduction")
            -- print("最爱orangegem223")
            inst.ORANGESHIELD = SpawnPrefab("obsword_orangeshield")
            inst.ORANGESHIELD.entity:SetParent(inst.entity)
        end,
        cancelextratalent = function(inst)
            local inst = inst.components.inventoryitem.owner
            if inst:HasTag("obsword_orangegem_reduction") then
                inst:RemoveTag("obsword_orangegem_reduction")
                inst.components.health.externalabsorbmodifiers:RemoveModifier(inst, "orangegem_reduction")
                inst.ORANGESHIELD:Remove()
                inst.ORANGESHIELD = nil
            end
        end,
        onattack = function(owner, target, inst)
            if owner.speedtask ~= nil then
                owner.speedtask = function(owner)
                    owner.components.locomotor.runspeed = owner.components.locomotor.runspeed + 1.5
                    owner.components.locomotor.walkspeed = owner.components.locomotor.walkspeed + 1.5
                    owner:DoTaskInTime(5, function()
                        owner.components.locomotor.runspeed = owner.components.locomotor.runspeed - 1.5
                        owner.components.locomotor.walkspeed = owner.components.locomotor.walkspeed - 1.5
                    end)
                end
            end
            if not target.components.locomotor and target.components.health then
                target.components.health:DoDelta(-100)
            end
            if target.components.locomotor and math.random(1, 8) < 6 then
                obsword_orangerepair(owner)
                local x, y, z = target.Transform:GetWorldPosition()
                local sand = SpawnPrefab("sandspike_short")
                sand.Transform:SetPosition(x, 0, z)
                sand:DoTaskInTime(5, function()
                    sand:Remove()
                end)
            end
        end
    },
--一定概率打落掉落物，史诗级目标概率更低  回复耐久 使用度 护甲值 新鲜度 攻击有额外能量恢复
    ["greengem"] = {
        extarpower = 50,
        onattack = function(owner, target, inst)
            --   平a同一个目标五下恢复一定生命  六下随机恢复一定能量
            owner.components.obrsword_power:DoDelta(3)

            if not target.components.obrsword_powergem_sign then
                target:AddComponent("obrsword_powergem_sign")

                target.components.obrsword_powergem_sign.greengemlevel = 1
            else
                target.components.obrsword_powergem_sign.greengemlevel =
                    target.components.obrsword_powergem_sign.greengemlevel + 1
                if target.components.obrsword_powergem_sign.greengemlevel == 6 then
                    target.components.obrsword_powergem_sign.greengemlevel = 0
                end
            end

            if target.components.obrsword_powergem_sign.greengemlevel == 2 then
                local op = owner.components.obrsword_power.current
                local numcover = clamp((3 + 0.1 * op), 0, 18)
                owner.components.health:DoDelta(numcover)
                SpawnPrefab("farm_plant_happy").Transform:SetPosition(owner.Transform:GetWorldPosition())
            end

            if target.components.obrsword_powergem_sign.greengemlevel == 5 then
                SpawnPrefab("wolfgang_mighty_fx").Transform:SetPosition(owner.Transform:GetWorldPosition())
                local op = obsword_repair(owner)
                local op1 = mount_re * 5
                owner.components.obrsword_power:DoDelta(math.random(op1, op1 + 15))
            end
        end,
        extratalent = function(inst) end,
        cancelextratalent = function(inst) end,

    },

    ["yellowgem"] = {
        -- 大量能量提升  每秒对附近范围怪 物/暗影 造成随机伤害  产生光圈随身
        onattack = function(owner, target, inst)
        end,
        extarpower = 80,

        extratalent = function(inst)
            local owner = inst.components.inventoryitem.owner
            --精神与光永存
            inst.obr_yellowgem_task = inst:DoPeriodicTask(2.5, function(inst)
                owner.components.sanity:DoDelta(-1)
                owner.components.obrsword_power:DoDelta(-2.5)
                local musttags = { "_health", "_combat" }
                local notags = { "player" }
                local pos = Vector3(owner.Transform:GetWorldPosition())
                local ents = TheSim:FindEntities(pos.x, pos.y, pos.z, 5, musttags, notags)
                for k, v in pairs(ents) do
                    if v:HasTag("monster") or v:HasTag("shadow") then
                        v.components.combat:GetAttacked(owner, math.random(33, 101))
                        v:DoTaskInTime(1, function()
                            v.components.combat:GetAttacked(owner, math.random(33, 101))
                        end)
                        local x, y, z = v.Transform:GetWorldPosition()
                        local lightfx = SpawnPrefab("winters_feast_depletefood")
                        lightfx.Transform:SetPosition(x, y, z)
                    end
                    --遇见织影者时将迸发更闪亮光芒
                    if v:HasTag("epic") and v:HasTag("stalker") and owner.yellowgemtask2 == nil then
                        owner.yellowgemtask2 = owner:DoPeriodicTask(2.5, function(owner)
                            owner.components.obrsword_power:DoDelta(-5)

                            local lightfx1 = SpawnPrefab("fx_book_light_upgraded")
                            local opfx = SpawnPrefab("moonpulse_fx")
                            lightfx1.entity:SetParent(owner.entity)
                            opfx.entity:SetParent(owner.entity)
                            local musttags = { "_health", "monster" }
                            local notags = { "player" }
                            local pos = Vector3(owner.Transform:GetWorldPosition())
                            local ents = TheSim:FindEntities(pos.x, pos.y, pos.z, 16, musttags, notags)
                            for k, v in pairs(ents) do
                                if v:HasTag("monster") or v:HasTag("shadow") then
                                    v.components.combat:GetAttacked(owner, math.random(50, 101))
                                    v:DoTaskInTime(1.5, function()
                                        v.components.combat:GetAttacked(owner, math.random(50, 101))
                                    end)
                                end
                            end
                        end)
                        owner:DoTaskInTime(15, function()
                            if owner.yellowgemtask2 ~= nil then
                                owner.yellowgemtask2:Cancel()
                                owner.yellowgemtask2 = nil
                            end
                        end)
                    end
                end
            end)
            if inst._light == nil then                   -- 如果没有光
                inst._light = SpawnPrefab("sword_light") -- 那么就产生光
            end
            inst._light.entity:SetParent((inst._body or owner or inst).entity)
        end,

        cancelextratalent = function(inst)
            if inst._light ~= nil then -- 如果有光
                inst._light:Remove()   -- 那么移除这个光
                inst._light = nil
            end
            if inst.obr_yellowgem_task ~= nil then
                inst.obr_yellowgem_task:Cancel()
                inst.obr_yellowgem_task = nil
            end
        end
    },
    ["opalpreciousgem"] = {

        -- 巨量能量提升  对目标赋予欧布印记 3环最大生命伤害  凝聚能量不再降低  免疫噩梦光环
        extarpower = 200,
        extratalent = function(inst)
            local owner = inst.components.inventoryitem.owner
            owner:AddTag("obsword_mapgoto")
            owner.components.obrsword_power.opalpreciousgem = true
            owner.components.sanity.neg_aura_modifiers:SetModifier(owner, 0, "neg_sanity_reduction")
        end,

        cancelextratalent = function(inst)
            local owner = inst.components.inventoryitem.owner
            if owner:HasTag("obsword_mapgoto") then
                owner:RemoveTag("obsword_mapgoto")
            end
            owner.components.sanity.neg_aura_modifiers:RemoveModifier(owner, "neg_sanity_reduction")
            owner.components.obrsword_power.opalpreciousgem = false
        end,
        onattack = function(owner, target, inst)
            if target.listened_tri_circle == nil then
                target:ListenForEvent('attacked', function(inst, data)
                    if data.weapon and data.weapon.prefab and data.weapon.prefab == "obrsword" then
                    else
                        return
                    end
                    if inst and inst.components and inst.components.health and not inst.components.health:IsDead() then
                    else
                        return
                    end
                    if inst.listened_tri_circle == nil then
                        inst.listened_tri_circle = true
                    end
                    if 1 then
                        if inst.tri_circle == nil then
                            inst.tri_circle = 1
                        else
                            inst.tri_circle = inst.tri_circle + 1
                        end
                        if inst.tri_circle == 1 then
                            if inst.tri_circle_fx_1 == nil then
                                inst.tri_circle_fx_1 = SpawnPrefab('reticule')
                                inst.tri_circle_fx_1.Transform:SetScale(1.5, 1.5, 1.5)
                                inst.tri_circle_fx_1.entity:SetParent(inst.entity)
                                inst.tri_circle_fx_1.entity:AddFollower()
                                inst.tri_circle_fx_1.Follower:FollowSymbol(inst.GUID, nil, 0, 0, 0)
                            end
                        end
                        if inst.tri_circle == 2 then
                            if inst.tri_circle_fx_2 == nil then
                                inst.tri_circle_fx_2 = SpawnPrefab('reticule')
                                inst.tri_circle_fx_2.Transform:SetScale(2, 2, 2)
                                inst.tri_circle_fx_2.entity:SetParent(inst.entity)
                                inst.tri_circle_fx_2.entity:AddFollower()
                                inst.tri_circle_fx_2.Follower:FollowSymbol(inst.GUID, nil, 0, 0, 0)
                            end
                        end

                        if inst.tri_circle == 3 then
                            if inst.tri_circle_fx_1 then
                                inst.tri_circle_fx_1:Remove()
                                inst.tri_circle_fx_1 = nil
                            end
                            if inst.tri_circle_fx_2 then
                                inst.tri_circle_fx_2:Remove()
                                inst.tri_circle_fx_2 = nil
                            end
                            local circle_blow_fx = SpawnPrefab('explode_small_slurtlehole')
                            circle_blow_fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
                            circle_blow_fx.Transform:SetScale(math.random(2, 5) / 2, math.random(2, 5) / 2,
                                math.random(2, 5) / 2)
                            inst.SoundEmitter:PlaySound('dontstarve/common/whip_large')
                            inst.tri_circle = 0 -- 由于后面还要追加一次伤害,所以这里写成-1不是0
                            local percentage_dmg = 1.5 / 100
                            local bonus_dmg = inst.components.health.maxhealth * percentage_dmg
                            -- declare(nil,'dmg:'..bonus_dmg)
                            inst.components.combat:GetAttacked(data.attacker, bonus_dmg)
                        end
                        -- declare(nil,'cirecle:'..inst.tri_circle)
                    end
                end)
            end
        end

    },
    ["panflute"] = {
        -- 播放飘渺的呼唤  缓慢增加sanity  血量  能量，减少饥饿值
        onattack = function(owner, target, inst)
        end,
        extarpower = 70,

        extratalent = function(inst)
            inst:DoTaskInTime(0.1, function()
                inst.SoundEmitter:PlaySound("obrost/obr/obrbgm", "obrbgm", .8) -- 音效
            end)

            local owner = inst.components.inventoryitem.owner
            owner.components.hunger.burnratemodifiers:SetModifier(owner, 2.5, "panflute_burn")
            inst.cutetask = inst:DoPeriodicTask(2, function()
                local x, y, z = inst.Transform:GetWorldPosition()
                local ents = TheSim:FindEntities(x, y, z, 3, "player")
                for k, v in pairs(ents) do
                    if v.components.health and v.entity:IsVisible() then
                        if v.components.obrsword_power then
                            v.components.obrsword_power:DoDelta(1.5)
                        end
                        if v.components.sanity then
                            v.components.sanity:DoDelta(0.25)
                        end
                    end
                end
            end)
        end,
        cancelextratalent = function(inst)
            local owner = inst.components.inventoryitem.owner

            owner.components.hunger.burnratemodifiers:RemoveModifier(owner, "panflute_burn")
            inst.SoundEmitter:KillSound("obrbgm")
            if inst.cutetask ~= nil then
                inst.cutetask:Cancel()
                inst.cutetask = nil
            end
        end,
    },
}
function obrsword_gempower.losegem(inst)
    for k, v in pairs(obrsword_gempower) do
        if type(v) == "table" and v.cancelextratalent then
            v.cancelextratalent(inst)
        end
    end
    local owner = inst.components.inventoryitem.owner
    if owner == nil then return end

    owner.components.obrsword_power.extrapower = 0

    local ex = owner.components.obrsword_power.extrapower + 100

    owner.components.obrsword_power:SetMax(ex)
end

function obrsword_gempower.getgempower(inst, data)
    local owner = inst.components.equippable:IsEquipped() and inst.components.inventoryitem.owner or nil
    if owner == nil then
        return
    end
    local item = data.item
    if item ~= nil then
        obrsword_gempower[item.prefab].extratalent(inst)

        --[[local item = data.item
    if item ~= nil then
        if item.prefab == "yellowgem" then
            obrsword_gempower.yellowgem.onswordopen(owner, inst)
            owner.yellowtask2 = owner:DoPeriodicTask(3, function()
                obrsword_gempower.yellowgem.swordtask(owner, inst)
            end)

        end
        if item.prefab == "panflute" then obrsword_gempower.panflute.extratalent(inst) end
        if item.prefab == "opalpreciousgem" then
            obrsword_gempower.opalpreciousgem.addtag(owner)
        end
        if item.prefab == "orangegem" then

            obrsword_gempower.orangegem.extratalent(owner)

        end]] --

        owner.components.obrsword_power.extrapower = obrsword_gempower[item.prefab].extarpower

        local ex = owner.components.obrsword_power.extrapower + 100

        owner.components.obrsword_power:SetMax(ex)
    end
end

function obrsword_gempower.checkandchange(owner, target, inst)
    inst.components.container:FindItem(function(item)
        if item ~= nil then
            obrsword_gempower[item.prefab].onattack(owner, target, inst)

            if math.random(1, 8) < 4 and obrsword_gempower.fightbgmcd == true and TUNING.Obrsword_nab then
                inst.SoundEmitter:PlaySound("obrost/obr/obrfight1", nil, .5) -- 音效
                obrsword_gempower.fightbgmcd = false
                inst.fightbgmcd = inst:DoTaskInTime(36, function()
                    obrsword_gempower.fightbgmcd = true
                    if inst.fightbgmcd ~= nil then
                        inst.fightbgmcd = nil
                    end
                end)
            end
        end
    end)
end

return obrsword_gempower
